package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.data.CustAttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.common.exception.BssException;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 起止时间校验
 */
public class CheckHtStartEndTimeAttrHandler extends AbstractAttrHandler<KiteInst, CustAttrData> {
    @Override
    public void before(KiteAttr attr, KiteInst inst, String value, CustAttrData data) {
        if (KiteStringUtils.isEqual("210004448", attr.getFieldName())) { //合同约定开始时间
            KiteAttr endTimeAttr = inst.getAttr("210004449");
            if (KiteStringUtils.isNotEmpty(value) && KiteStringUtils.isNotEmpty(endTimeAttr.getValue())) {
                Date startDate = simpleHtDate(value);
                Date endDate = simpleHtDate(endTimeAttr.getValue());
                if (startDate!=null&&startDate.after(endDate)) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "","合同约定开始时间必须小于合同约定到期时间");
                }
            }
        }

        if (KiteStringUtils.isEqual("210004449", attr.getFieldName())) { //合同约定到期时间
            KiteAttr startTimeAttr = inst.getAttr("210004448");
            if (KiteStringUtils.isNotEmpty(value) && KiteStringUtils.isNotEmpty(startTimeAttr.getValue())) {
                Date startDate = simpleHtDate(startTimeAttr.getValue());
                Date endDate = simpleHtDate(value);
                if (startDate.after(endDate)) {
                    BssException.throwOut(KeyConsts.LOG_MODULE, "","合同约定到期时间必须大于合同约定开始时间");
                }
            }
        }
    }

    @Override
    public void set(KiteAttr attr, KiteInst inst, String value, CustAttrData data) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if(value!=null&&!value.contains("-")){
            value = df.format(simpleHtDate(value));
            attr.setValue(value);
            attr.setValueDesc(value);
        }
        super.set(attr, inst, value, data);
    }

    private Date simpleHtDate(String dateV){
        Date dateD = null;
        if(dateV.contains("-")){
            dateD = DateFormatUtils.parseStrToDate(dateV);
        }else {
            SimpleDateFormat dateFormator = new SimpleDateFormat("yyyyMMddHHmmss");
            dateD = dateFormator.parse(dateV, new ParsePosition(0));
            if(null==dateD){
                SimpleDateFormat dateFormator1 = new SimpleDateFormat("yyyyMMdd");
                dateD = dateFormator1.parse(dateV, new ParsePosition(0));
            }
        }
        return dateD;
    }
}
